<template>
  <div class="box">
    <!-- action为上传的地址 -->
    <a-upload
      action=""
      list-type="picture-card"
      v-model:file-list="fileList"
      :customRequest="customRequest"
      :before-upload="beforeUpload"
      @preview="handlePreview"
      :disabled="disabled"
      @change="handleChange"
    >
      <div v-if="!fileNumber || fileList.length < fileNumber">
        <plus-outlined />
      </div>
    </a-upload>

    <!-- 图片预览弹框 -->
    <a-image
      :src="previewImage"
      :style="{ display: 'none' }"
      :preview="{
        visible: previewVisible,
        onVisibleChange: value => {
          previewVisible = value
        }
      }"
    ></a-image>
  </div>
</template>
<script>
import { PlusOutlined } from '@ant-design/icons-vue'

/**
 * 照片提交组件(使用Ant Design中的图片上传功能 )
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2021/9/8 14:00
 */

// 转换图片格式的方法
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  data() {
    return {
      // 控制图片预览弹出层的显示与隐藏
      previewVisible: false,
      // 预览图片弹出层的图片路径
      previewImage: '',
      loading: false,
      // 文件列表
      fileList: []
    }
  },
  components: {
    PlusOutlined
  },
  props: {
    // 图片回显集合
    photoList: {
      type: Array,
      default: []
    },
    // 最大图片数量
    fileNumber: {
      type: [Number, String, null],
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false // 是否禁用
    }
  },
  watch: {
    photoList: {
      handler(newValue, oldValue) {
        console.log(newValue, oldValue)
        if (newValue) {
          this.fileList = newValue
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     *  打开图片预览
     */
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    /**
     *  上传图片
     */
    async customRequest(file) {
      const params = new FormData()
      params.append('image', file.file)
      const url = await getBase64(file.file)
      this.$emit('getImg', params, url)
    },

    /**
     *  上传拦截
     */
    beforeUpload(file, fileList) {
      return new Promise((resolve, reject) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type.includes('icon') //|| file.type === 'image/x-icon'
        if (!isJpgOrPng) {
          fileList.splice(fileList.indexOf(file), 1)
          this.$message.error('请上传jpg/png/ico图片!')
          return reject(false)
        }
        const isMaxSize = file.size / 1024 / 1024 < 10
        if (!isMaxSize) {
          fileList.splice(fileList.indexOf(file), 1)
          this.$message.error('图片大小不能超过10M!')
          return reject(false)
        }
        return resolve(true)
      })
    },

    handleChange(info) {
      //将最终的文件列表赋值给自定义的fileList容器。
      //如果beforeUpload中返回的是false的话，那么
      if (info.file.status === undefined) this.fileList = []
      else this.fileList = info.fileList
    },
    /**
     *  删除
     */
    remove(file) {
      const self = this
      this.$confirm({
        title: '请确定是否删除?',
        onOk() {
          self.fileList = self.fileList.filter(v => v.uid !== file.uid)
        },
        onCancel() {}
      })
    },
    loadData(eventData) {
      this.fileList = []
      if (!eventData) return // 赋值
      ;(eventData.imageInfos || []).forEach(item => {
        this.fileList.push({
          status: 'done',
          name: '图片',
          uid: item.eventFileId,
          url: item.imageUrl
        })
      })
    },
    getData(eventData) {
      // 取值
      eventData.imageInfos = this.fileList.map(item => {
        return {
          eventFileId: item.uid,
          eventId: this.eventId
        }
      })
    }
  },
  beforeMount() {
    this.fileList = []
  }
}
</script>
<style scoped lang="less">
/deep/.ant-upload-list-picture-card-container,
/deep/.ant-upload.ant-upload-select-picture-card,
/deep/.ant-upload-list-picture-card .ant-upload-list-item {
  width: 1.2rem;
  // height: 0.8rem;
  padding: 0;
}

.plus-icon {
  font-size: 0.2rem;
}
</style>
